package edu.spec.chenli.Listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Hashtable;
import java.util.Map;

//@WebListener()
public class OnLineListener implements HttpSessionListener{

    public  void sessionCreated(HttpSessionEvent se){
        HttpSession session=se.getSession();
        ServletContext application=session.getServletContext();
        //获取sessionID
        String sessionId=session.getId();
        //如果是一次新的会话
        if(session.isNew()){
            String user= (String) session.getAttribute("user");
            //未登录用户当游客处理
            user =(user==null)?"游客":user;
            Map<String,String> online=(Map<String, String>)application.getAttribute("online");
            if(online==null) {
                online = new Hashtable<String, String>();

            }
            //将用户在线信息放入map中
            online.put(sessionId, user);
            application.setAttribute("online",online);
        }
    }
    public void contextInitialized(ServletContextEvent sce) {
      /* This method is called when the servlet context is
         initialized(when the Web application is deployed). 
         You can initialize servlet context related data here.
      */
    }

    public void contextDestroyed(ServletContextEvent sce) {
      /* This method is invoked when the Servlet Context 
         (the Web application) is undeployed or 
         Application Server shuts down.
      */
    }

    public void sessionDestroyed(HttpSessionEvent se) {
       HttpSession session=se.getSession();
       ServletContext application=session.getServletContext();
       String sessionId=session.getId();
       Map<String,String> online=(Map<String, String>)application.getAttribute("online");
       if(online!=null){
           //删除该用户的在线信息
           online.remove(sessionId);
       }
       application.setAttribute("online",online);
    }

    // -------------------------------------------------------
    // HttpSessionAttributeListener implementation
    // -------------------------------------------------------

    public void attributeAdded(HttpSessionBindingEvent sbe) {
      /* This method is called when an attribute 
         is added to a session.
      */
    }

    public void attributeRemoved(HttpSessionBindingEvent sbe) {
      /* This method is called when an attribute
         is removed from a session.
      */
    }

    public void attributeReplaced(HttpSessionBindingEvent sbe) {
      /* This method is invoked when an attibute
         is replaced in a session.
      */
    }
}
